<!-- 生产日历 -->
<template>
  <basic-container>
    <div class="calendar-page">
      <div class="calendar-header">
        <div class="calendar-header-title">
          <div class="calendar-menu">
            <el-button type="primary" size="mini" icon="el-icon-edit-outline" v-if="permission.productCalendar_plan" @click="workTimeConfig">作业时间配置</el-button>
            <div class="weekStart">一周开始日：{{ weekStartDay }}</div>
          </div>
        </div>
        <div class="calendar-header-yaer">
          <div class="calendar-header-yaer-box" title="单击:变为非生产日 双击:设置特定日">
            <div class="color-box"></div>
            <div class="color-label">生产日</div>
          </div>
          <div class="calendar-header-yaer-box" title="单击:变为生产日 双击:设置特定日">
            <div class="color-box default"></div>
            <div class="color-label">非生产日</div>
          </div>
          <div class="calendar-header-yaer-box" title="单击:变为非生产日 双击:编辑/查看特定日">
            <div class="color-box special"></div>
            <div class="color-label">特定日</div>
          </div>
          <div class="year">
            <div class="label">工段：</div>
            <el-select style="width: 150px; margin-right: 20px" v-model="section.data" @change="initTimeDatas" filterable>
              <el-option v-for="item in section.options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
            <div class="label">年份：</div>
            <el-date-picker
              :clearable="false"
              style="width: 120px"
              v-model="pickerYear"
              type="year"
              placeholder="选择年"
              format="yyyy"
              value-format="yyyy"
              @change="initTimeDatas"
            >
            </el-date-picker>
          </div>
        </div>
      </div>

      <div
        class="calendar-content"
        v-loading="loading"
        element-loading-text="生产日历数据加载中"
        element-loading-spinner="el-icon-loading"
        :style="{ width: typeof width == 'number' ? width + 'px' : width }"
      >
        <div v-for="(item, index) in timeDatas" :key="item.month" class="monthArea">
          <div class="header">
            <span class="time">{{ item.month }}月</span>
          </div>
          <div class="content">
            <!-- 星期 -->
            <div class="content-header">
              <div class="wItem" v-for="(wItem, wIndex) in weekHearders" :key="wIndex">{{ wItem }}</div>
            </div>
            <!-- 单元格日期 -->
            <div class="content-wrap">
              <!-- :title="tItem.isSpecialDay ? '取消特定日' : tItem.isActive ? '设为非生产日/特定日' : '设为生产日/特定日'" -->
              <div
                class="tItem"
                :class="{
                  isActive: tItem.isActive,
                  isSpecialDay: tItem.isSpecialDay
                }"
                :style="computedItemStyle(tItem)"
                v-for="(tItem, tIndex) in timeDatas[index].time"
                :key="tIndex"
                @click="selectItem(tItem)"
                @dblclick="handleDblClick(tItem)"
              >
                {{ tItem.time.split('-')[2] }}
              </div>
            </div>
            <!-- 周 -->
            <div class="week">
              <div class="sitg">周</div>
              <div v-for="w in weekArrays[index]" :key="w" class="cell">{{ w }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 修改日期状态 -->
    <el-dialog custom-class="dayStatusDialog" title="操作" :visible.sync="dayStatusDialog.visible" width="30%" append-to-body>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" v-if="dayStatusDialog.isWorkday == 1" @click="setNotWorkDay()">设为非生产日</el-button>
        <el-button type="primary" size="small" v-else @click="setWorkDay()">设为生产日</el-button>
        <el-button type="primary" size="small" @click="setSpecialDay()">设为特定日</el-button>
        <el-button size="small" @click="dayStatusDialog.visible = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 作业时间设置 -->
    <el-dialog
      custom-class="workTimeDialog"
      title="作业时间设置"
      append-to-body
      :visible.sync="workTimeConfigDialog.visible"
      top="3vh"
      width="80%"
      @close="closeWorkTimeConfigDialog"
    >
      <el-tabs type="border-card" v-model="workTimeConfigDialog.tabsIndex" @tab-click="handleTabClick">
        <el-tab-pane label="日作业时间方案" name="1">
          <avue-crud
            ref="crud"
            v-model="workTimeConfigDialog.time.form"
            :option="workTimeConfigDialog.time.option"
            :table-loading="workTimeConfigDialog.time.loading"
            :page.sync="workTimeConfigDialog.time.page"
            :data="workTimeConfigDialog.time.data"
            @row-update="rowUpdate"
            @row-del="workTimeConfigRowDel"
          >
            <template slot-scope="scope" slot="menuLeft">
              <el-button type="primary" icon="el-icon-plus" size="small" @click="handleWorkTimeAdd"> 新 增</el-button>
            </template>
            <template slot-scope="{ row }" slot="menu">
              <el-button type="text" icon="el-icon-edit" size="small" @click="handleWorkTimeEdit(row)">编 辑</el-button>
            </template>
          </avue-crud>
        </el-tab-pane>
        <el-tab-pane label="日历方案" name="2">
          <avue-crud
            ref="dayCrud"
            v-model="workTimeConfigDialog.day.form"
            :before-open="beforeWorkDayOpen"
            :option="workTimeConfigDialog.day.option"
            :table-loading="workTimeConfigDialog.day.loading"
            :page.sync="workTimeConfigDialog.day.page"
            :data="workTimeConfigDialog.day.data"
            @row-update="handleWorkDayUpdate"
            @row-save="handleWorkDayAdd"
            @row-del="workDayRowDel"
          >
          </avue-crud>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-circle-close" @click="closeWorkTimeConfigDialog">关闭</el-button>
        <el-button type="primary" size="small" v-if="workTimeConfigDialog.tabsIndex == '1'" icon="el-icon-right" @click="nextStep">下一步</el-button>
        <el-button type="primary" size="small" v-if="workTimeConfigDialog.tabsIndex == '2'" icon="el-icon-circle-plus-outline" @click="saveWorkDayConfig">提交</el-button>
      </div>
    </el-dialog>

    <!-- 日作业时间方案 新增/编辑  -->
    <el-dialog
      custom-class="workTimeConfigDialog"
      :title="workTimeConfigTitle"
      top="3vh"
      :append-to-body="true"
      width="50%"
      v-if="workTimeConfigDialog.time.visible"
      :visible.sync="workTimeConfigDialog.time.visible"
      @close="closeWorkTimeAddFormDialog"
    >
      <el-form ref="workTimeAddForm" :model="workTimeAddForm" :rules="rules" label-width="120px" v-if="workTimeConfigTitle != '特定日作业时间设置'">
        <div class="dispatch-title">
          <div class="dispatch-title-dot"></div>
          <div class="dispatch-title-text">基本信息</div>
        </div>
        <div class="dispatch-baseInfo">
          <el-form-item label="作业时间方案：" prop="name" class="inline">
            <el-input size="mini" v-model="workTimeAddForm.name" placeholder="请输入作业时间方案"></el-input>
          </el-form-item>
          <el-form-item label="作业时间编码：" prop="code" class="inline">
            <el-input size="mini" v-model="workTimeAddForm.code" placeholder="请输入作业时间编码"></el-input>
          </el-form-item>
        </div>
        <div class="dispatch-title">
          <div class="dispatch-title-dot"></div>
          <div class="dispatch-title-text">作业时间配置</div>
        </div>
        <div class="timeItemArea">
          <div class="timeItem" v-for="(detail, detailIndex) in workTimeAddForm.details" :key="detailIndex">
            <div class="closeIcon" @click="handleCloseTimeItem(detailIndex)">X</div>
            <el-form-item
              :key="detailIndex"
              label="星期选择："
              :prop="'details.' + detailIndex + '.weekday'"
              class="inline"
              :rules="{
                required: true,
                trigger: 'change',
                message: '请选择星期'
              }"
            >
              <el-select size="small" multiple collapse-tags v-model="detail.weekday" placeholder="请选择星期">
                <el-option label="周一" value="MONDAY"></el-option>
                <el-option label="周二" value="TUESDAY"></el-option>
                <el-option label="周三" value="WEDNESDAY"></el-option>
                <el-option label="周四" value="THURSDAY"></el-option>
                <el-option label="周五" value="FRIDAY"></el-option>
                <el-option label="周六" value="SATURDAY"></el-option>
                <el-option label="周日" value="SUNDAY"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="inline"> 作业工时（H）：{{ detail.workHour }} </el-form-item>

            <el-form-item
              v-for="(jobTime, jobIndex) in detail.jobTimeData"
              :key="detail + jobIndex"
              :label="jobIndex == 0 ? '作业时段：' : ''"
              :prop="'details.' + detailIndex + '.jobTimeData.' + jobIndex + '.jobEndTime'"
              :rules="{
                required: true,
                validator: validateTime,
                trigger: 'change',
                times: jobTime
              }"
            >
              <el-time-picker
                size="small"
                format="HH:mm"
                value-format="HH:mm"
                v-model="jobTime.jobStartTime"
                placeholder="选择开始时间"
                @change="handleCalculateWorkHour(detailIndex)"
              >
              </el-time-picker>
              <span style="margin: 0 10px">至</span>
              <el-time-picker
                size="small"
                format="HH:mm"
                value-format="HH:mm"
                v-model="jobTime.jobEndTime"
                placeholder="选择结束时间"
                @change="handleCalculateWorkHour(detailIndex)"
              >
              </el-time-picker>

              <el-button
                v-if="detail.jobTimeData.length != 1"
                size="mini"
                type="danger"
                class="deleteTime"
                icon="el-icon-delete"
                circle
                @click="handleDeleteJobTime(detailIndex, jobIndex)"
              >
              </el-button>
              <el-button
                v-if="jobIndex == detail.jobTimeData.length - 1"
                size="mini"
                type="primary"
                class="addTime"
                icon="el-icon-plus"
                circle
                @click="handleAddJobTime(detailIndex)"
              ></el-button>
            </el-form-item>
          </div>
        </div>

        <el-button class="timeConfig" size="mini" type="primary" icon="el-icon-plus" @click="handleTimeAddConfig">新增时间配置</el-button>
      </el-form>

      <el-form class="specialDayForm" ref="workTimeAddForm" :model="workTimeAddForm" :rules="rules" label-width="120px" v-else>
        <el-form-item label="特定日期：" class="inline">
          <el-time-picker
            size="small"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            :clearable="false"
            :disabled="true"
            v-model="workTimeAddForm.specialDay"
            placeholder="选择日期"
          >
          </el-time-picker>
        </el-form-item>
        <el-form-item class="inline">作业工时（H）：{{ workTimeAddForm.details[0].workHour }}</el-form-item>
        <div class="workhourArea">
          <el-form-item
            :prop="'details.' + 0 + '.jobTimeData.' + index + '.jobEndTime'"
            :rules="{
              required: true,
              validator: validateTime,
              times: item,
              trigger: 'change'
            }"
            :label="index == 0 ? '作业时段：' : ''"
            v-for="(item, index) in workTimeAddForm.details[0].jobTimeData"
            :key="index"
          >
            <el-time-picker
              size="small"
              format="HH:mm"
              value-format="HH:mm"
              v-model="item.jobStartTime"
              :clearable="false"
              placeholder="选择开始时间"
              @change="handleCalculateWorkHour(0)"
            >
            </el-time-picker>
            <span style="margin: 0 10px">至</span>
            <el-time-picker
              size="small"
              format="HH:mm"
              value-format="HH:mm"
              v-model="item.jobEndTime"
              :clearable="false"
              placeholder="选择结束时间"
              @change="handleCalculateWorkHour(0)"
            >
            </el-time-picker>
            <el-button
              v-if="workTimeAddForm.details[0].jobTimeData.length != 1"
              size="mini"
              type="danger"
              class="deleteTime"
              icon="el-icon-delete"
              circle
              @click="handleDeleteJobTime(0, index)"
            >
            </el-button>
            <el-button
              v-if="index == workTimeAddForm.details[0].jobTimeData.length - 1"
              size="mini"
              type="primary"
              class="addTime"
              icon="el-icon-plus"
              circle
              @click="handleAddJobTime(0)"
            ></el-button>
          </el-form-item>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-circle-close" @click="closeWorkTimeAddFormDialog">取消</el-button>
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="workTimeConfigSubmit">保存</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import layout, { getWeekArray } from '@/util/layout';
import {
  getCalendarDetail,
  initCalendar,
  getCalendarDayTemplateList,
  deleteCalendarDayTemplate,
  calculateWorkHour,
  submitCalendarDayTemplate,
  getWeekdayKeyValue,
  getCalendarPage,
  deleteCalendar,
  calendarSubmitSpecialDay,
  getCalendarSection,
  checkCalendar
} from '@/api/product/productCalendar.js';
import { getAllSection } from '@/api/product/sectionDefinition';
import { getParamDetail } from '@/api/system/param';
import { mapGetters } from 'vuex';
export default {
  name: 'calendar',
  components: {
    CommonModalTemplate
  },
  data() {
    return {
      section: {
        options: [],
        data: ''
      },
      timer: null,
      initCalendarDay: 1, // 一周从周一开始计算
      dayStatusDialog: {
        visible: false,
        isWorkday: 0,
        dayData: {}
      },
      loading: false,
      calendarId: null,
      cancelData: [], // 每次取消数据
      addData: [], // 每次新增数据
      modalData: [], // 后台返回这些生产日集合
      weekArrays: [], // 周总数据 （用于渲染出整个日历的周）
      timeDatas: [], // 日历总数据（用于渲染出整个日历）
      weekHearders: ['一', '二', '三', '四', '五', '六', '日'],
      year: new Date().getFullYear(),
      pickerYear: new Date().getFullYear() + '',
      month: new Date().getMonth() + 1,
      date: new Date().getDate(),
      workTimeConfigTitle: '新增',
      allSectionData: [],
      defaultWorkingDay: [], // 默认生产日
      // 作业时间设置
      workTimeConfigDialog: {
        visible: false,
        tabsIndex: '1',
        // 作业时间方案
        time: {
          visible: false,
          page: {
            pageSize: 20,
            currentPage: 1,
            total: 0
          },
          option: {
            height: 'calc(100vh - 500px)',
            calcHeight: 30,
            tip: false,
            searchShow: true,
            searchMenuSpan: 5,
            border: true,
            index: true,
            indexLabel: '序号',
            viewBtn: false,
            viewTitle: '详情',
            editBtn: false,
            delBtn: true,
            addBtn: false,
            page: true,
            selection: false,
            dialogClickModal: false,
            menu: true,
            menuWidth: 150,
            labelWidth: 160,
            dialogDrag: true,
            highlightCurrentRow: true,
            columnBtn: false,
            refreshBtn: false,
            column: [
              {
                label: '作业时间方案',
                prop: 'name',
                overHidden: true
              },
              { label: '作业时间编码', prop: 'code', overHidden: true },
              {
                label: '日期选择',
                prop: 'weekdayStr',
                overHidden: true
              },
              {
                label: '作业时段',
                prop: 'jobTimeDataStr',
                overHidden: true
              },
              {
                label: '作业工时',
                prop: 'workHourStr',
                overHidden: true
              }
            ]
          },
          data: [],
          loading: false,
          form: {}
        },
        // 日历方案
        day: {
          visible: false,
          page: {
            pageSize: 20,
            currentPage: 1,
            total: 0
          },
          option: {
            height: 'calc(100vh - 500px)',
            calcHeight: 30,
            tip: false,
            searchShow: true,
            searchMenuSpan: 5,
            border: true,
            index: true,
            indexLabel: '序号',
            viewBtn: false,
            viewTitle: '详情',
            editBtn: true,
            delBtn: true,
            addBtn: true,
            page: true,
            selection: false,
            dialogClickModal: false,
            menu: true,
            menuWidth: 150,
            labelWidth: 120,
            highlightCurrentRow: true,
            columnBtn: false,
            refreshBtn: false,
            column: [
              {
                label: '日历方案',
                prop: 'name',
                order: 1,
                rules: [
                  {
                    required: true,
                    message: '请输入日历方案',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '日历编码',
                prop: 'code',
                order: 2,
                rules: [
                  {
                    required: true,
                    message: '请输入日历编码',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '使用工段',
                prop: 'sectionNames',
                overHidden: true,
                addDisplay: false,
                editDisplay: false
              },
              {
                label: '使用工段',
                prop: 'sectionIds',
                order: 5,
                span: 24,
                labelTip: '若不选择使用工段，则默认该作业日方案为工厂级。',
                hide: true,
                dicData: [],
                type: 'select',
                multiple: true,
                rules: [
                  {
                    required: true,
                    message: '请选择使用工段',
                    trigger: 'change'
                  }
                ],
                change: ({ value }) => {
                  this.handleChangeSectionIds(value);
                }
              },
              {
                label: '开始日期',
                prop: 'fromDate',
                type: 'date',
                order: 3,
                format: 'yyyy-MM-dd',
                valueFormat: 'yyyy-MM-dd',
                pickerOptions: {
                  shortcuts: [
                    {
                      text: '去年年初',
                      onClick(picker) {
                        const date = new Date();
                        date.setTime(new Date(date.getFullYear() - 1, 0, 1).getTime());
                        picker.$emit('pick', date);
                      }
                    },
                    {
                      text: '今年年初',
                      onClick(picker) {
                        const date = new Date();
                        date.setTime(new Date(date.getFullYear(), 0, 1).getTime());
                        picker.$emit('pick', date);
                      }
                    },
                    {
                      text: '明年年初',
                      onClick(picker) {
                        const date = new Date();
                        date.setTime(new Date(date.getFullYear() + 1, 0, 1).getTime());
                        picker.$emit('pick', date);
                      }
                    }
                  ]
                },
                rules: [
                  {
                    required: true,
                    message: '请输入开始日期',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '结束日期',
                prop: 'toDate',
                type: 'date',
                order: 4,
                format: 'yyyy-MM-dd',
                valueFormat: 'yyyy-MM-dd',
                pickerOptions: {
                  shortcuts: [
                    {
                      text: '去年年尾',
                      onClick(picker) {
                        const date = new Date();
                        date.setTime(new Date(date.getFullYear() - 1, 11, 31).getTime());
                        picker.$emit('pick', date);
                      }
                    },
                    {
                      text: '今年年尾',
                      onClick(picker) {
                        const date = new Date();
                        date.setTime(new Date(date.getFullYear(), 11, 31).getTime());
                        picker.$emit('pick', date);
                      }
                    },
                    {
                      text: '明年年尾',
                      onClick(picker) {
                        const date = new Date();
                        date.setTime(new Date(date.getFullYear() + 1, 11, 31).getTime());
                        picker.$emit('pick', date);
                      }
                    }
                  ]
                },
                rules: [
                  {
                    required: true,
                    message: '请输入结束日期',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '作业时间方案',
                prop: 'schemeId',
                type: 'select',
                dicData: [],
                span: 12,
                hide: true,
                change: ({ value }) => {
                  if (value) {
                    this.handleChangeDefaultWorkingDay(value);
                  }
                },
                rules: [
                  {
                    required: true,
                    message: '请选择作业时间方案',
                    trigger: 'change'
                  }
                ]
              },
              {
                label: '作业时间方案',
                prop: 'defaultFormatterWorkingDay',
                addDisplay: false,
                editDisplay: false
              }
            ]
          },
          data: [],
          loading: false,
          form: {}
        }
      },
      // 日作业时间新增/特定日作业时间设置
      workTimeAddForm: {
        name: '',
        code: '',
        details: [
          {
            workHour: '',
            weekday: '',
            jobTimeData: [
              {
                jobStartTime: '',
                jobEndTime: ''
              }
            ]
          }
        ]
      },
      rules: {
        code: [{ required: true, message: '请输入作业时间编码', trigger: 'blur' }],
        name: [{ required: true, message: '请输入作业时间方案', trigger: 'blur' }]
        // weekday: [{ required: true, message: '请选择星期', trigger: 'change' }],
        // jobTimeData: [{ required: true, message: '请选择作业时段', trigger: 'change' }]
      }
    };
  },
  computed: {
    ...mapGetters(['permission']),
    // 今天
    today() {
      return this.year + '-' + (this.month < 10 ? '0' + this.month : this.month) + '-' + (this.date < 10 ? '0' + this.date : this.date);
    },
    computedItemStyle() {
      return (item) => {
        // 将空位元素背景色设为白色
        if (!item.time) {
          return {
            'background-color': '#fff',
            color: '#fff'
          };
        } else {
          return {
            '--isSpecialDay-bg': '#e6a23c', // 特定日颜色
            '--isActive-bg': '#92c0e8', // 生产日颜色
            '--default-bg': '#a07d7d24' // 非生产日颜色
          };
        }
      };
    },
    weekStartDay() {
      switch (this.initCalendarDay) {
        case 0:
          return '周日';
        case 1:
          return '周一';
        case 2:
          return '周二';
        case 3:
          return '周三';
        case 4:
          return '周四';
        case 5:
          return '周五';
        case 6:
          return '周六';
        default:
          break;
      }
    }
  },
  created() {
    Promise.all([
      this.initCalendarStartDay(), // 获取生产日初始化方案参数配置
      this.getHasSection() // 获取已配置的工段列表
    ]).then(() => {
      console.log(this.section.options, ' this.section.options');
      this.initTimeDatas(); // 初始化数据
    });
  },
  methods: {
    async getHasSection() {
      let result = await getCalendarSection();
      let data = result.data.data;
      this.section.options = data.map((item) => {
        return {
          label: item.sectionName,
          value: item.sectionId
        };
      });
      if (this.section.options && this.section.options.length > 0) {
        this.section.data = this.section.options[0].value;
      }
    },
    async getAllSectionData() {
      let result = await getAllSection();
      let data = result.data.data;
      this.allSectionData = data.map((item) => {
        return {
          label: item.name,
          value: item.id,
          code: item.code
        };
      });
    },
    validateTime(rule, value, callback) {
      console.log(rule, value);
      if (rule.times) {
        if (!rule.times.jobStartTime) {
          callback(new Error('请选择开始时间'));
        }
        if (!rule.times.jobEndTime) {
          callback(new Error('请选择结束时间'));
        }
        if (!rule.times.jobStartTime && !rule.times.jobEndTime) {
          callback(new Error('请选择开始时间和结束时间'));
        }
        if (!this.compareDate(rule.times.jobStartTime, rule.times.jobEndTime)) {
          callback(new Error('结束时间不能小于开始时间'));
        }
      }
      callback();
    },

    compareDate(time1, time2) {
      var date = new Date();
      var a = time1.split(':');
      var b = time2.split(':');
      return date.setHours(a[0], a[1]) < date.setHours(b[0], b[1]);
    },
    initTimeDatas() {
      let result = [];
      for (let i = 0; i < 12; i++) {
        result.push({ month: i + 1, time: layout(this.year, i + 1, this.initCalendarDay) });
      }
      this.timeDatas = this.handleWorkTimeData(result);
      console.log(this.timeDatas, '2134234');
      // this.$moment.updateLocale('zh-cn', {
      //   week: {
      //     // 每周的第一天 0:周日 1：周1
      //     dow: 1,
      //     doy: 7 + 1 - 1
      //     // dow: 0,
      //     // doy: 7 + 0 - 1
      //   }
      // });

      console.log("this.$$moment('2024-01-01').week()", this.$moment('2024-01-01').format('w'));
      console.log("this.$$moment('2024-01-02').week()", this.$moment('2024-01-02').format('w'));
      console.log("this.$$moment('2024-12-31').week()", this.$moment('2024-12-31').format('w'));

      let weekArrays = this.timeDatas
        .map((item, index) => {
          return item.time.map((t) => {
            return t.time;
          });
        })
        .map((item, index, array) => {
          return [0, 7, 14, 21, 28, 35].map((t) => {
            if (item[t]) {
              if (index == 11 && t == 35) {
                return this.$moment(item[28]).week() + 1;
              } else {
                if (index == 11 && t == 28 && this.$moment(item[t]).week() == 1) {
                  return this.$moment(item[21]).week() + 1;
                }
                return this.$moment(item[t]).week();
              }
            } else {
              // 除了1月的第一周
              if (t == 0 && index != 0) {
                return this.$moment(array[index - 1][35] || array[index - 1][28]).week();
              } else if (t == 0 && index == 0) {
                // 1月的第一周
                let firstDay = this.year + '-01-01';
                return this.$moment(firstDay).week();
              }
            }
          });
        });
      this.weekArrays = weekArrays;
    },
    // 获取日历详情 (初始化生产日)
    handleWorkTimeData(data) {
      let sectionParam = this.section.data;
      if (sectionParam) {
        this.loading = true;
        getCalendarDetail(sectionParam, this.pickerYear)
          .then((res) => {
            if (res && res.status == 200) {
              let result = res.data.data;
              if (result && result.length > 0) {
                this.modalData = result;
                if (this.modalData) {
                  let modalDataMonths = [...new Set(this.modalData.map((m) => m.day.split('-')[1]).map((m) => Number(m)))];
                  for (let i = 0; i < data.length; i++) {
                    if (modalDataMonths.includes(i + 1)) {
                      let result = data[i].time.filter((t) => this.modalData.map((m) => m.day).includes(t.time));
                      result.map((w) => {
                        let modalDayData = this.modalData.find((m) => m.day == w.time);
                        w.id = modalDayData.id;
                        w.calendarId = modalDayData.calendarId; // 日历id
                        w.calendarDaySchemeId = modalDayData.calendarDaySchemeId; // 日时间方案id
                        w.isActive = modalDayData.runningFlag == 1;
                        w.isSpecialDay = modalDayData.runningFlag == 2;
                        w.isWorkday = modalDayData.runningFlag == 1;
                        w.workHour = modalDayData.workHour;
                        w.jobTimeData = modalDayData.jobTimeData;
                        w.weekday = modalDayData.weekday;
                        w.runningFlag = modalDayData.runningFlag;
                      });
                    }
                  }
                }
              }
            }
          })
          .catch(() => {})
          .finally(() => {
            setTimeout(() => {
              this.loading = false;
            }, 300);
          });
      }

      return data;
    },
    initCalendarStartDay(value) {
      this.year = value ? Number(value) : new Date().getFullYear();
      // 生产日初始化方案
      getParamDetail({ paramKey: 'calendar_start_sunday' })
        .then((res) => {
          if (res.data.code === 200) {
            if (res.data.data) {
              this.initCalendarDay = Number(res.data.data.paramValue);
            } else {
              this.initCalendarDay = 1;
            }

            switch (this.initCalendarDay) {
              case 1:
                this.weekHearders = ['一', '二', '三', '四', '五', '六', '日'];
                break;
              case 2:
                this.weekHearders = ['二', '三', '四', '五', '六', '日', '一'];
                break;
              case 3:
                this.weekHearders = ['三', '四', '五', '六', '日', '一', '二'];
                break;
              case 4:
                this.weekHearders = ['四', '五', '六', '日', '一', '二', '三'];
                break;
              case 5:
                this.weekHearders = ['五', '六', '日', '一', '二', '三', '四'];
                break;
              case 6:
                this.weekHearders = ['六', '日', '一', '二', '三', '四', '五'];
                break;
              case 0:
                this.weekHearders = ['日', '一', '二', '三', '四', '五', '六'];
                break;
              default:
                break;
            }
            this.$moment.updateLocale('zh-cn', {
              week: {
                // 每周的第一天 0:周日 1：周1
                dow: this.initCalendarDay,
                doy: 7 + this.initCalendarDay - 1
              }
            });
          }
        })
        .catch((err) => {});
    },
    // 单击 切换工作日与非工作日
    selectItem(item) {
      this.dayStatusDialog.dayData = structuredClone(item);
      if (this.timer) {
        // 如果定时器存在，说明已经进行了一次单击
        clearTimeout(this.timer); // 清除定时器
        this.timer = null;
        this.handleDblClick(item); // 执行双击事件
      } else {
        // 如果定时器不存在，说明是第一次单击
        this.timer = setTimeout(() => {
          // 设置定时器
          this.timer = null; // 定时器置空
          // 只能在日期上点击，空白处无效
          if (!item.time) {
            return false;
          }
          if (item.calendarId) {
            this.calendarId = item.calendarId;
          }
          let params = {};
          if (item.isSpecialDay) {
            this.$confirm('是否确认将选中特定日变为非生产日？', '操作', {
              distinguishCancelAndClose: true,
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
              .then(() => {
                params = {
                  id: item.id,
                  weekday: item.weekday,
                  runningFlag: 0,
                  workHour: item.workHour,
                  jobTimeData: item.jobTimeData,
                  sectionId: this.section.data
                };
                calendarSubmitSpecialDay(params)
                  .then((res) => {
                    this.initTimeDatas(); //  初始化数据
                  })
                  .catch(() => {});
              })
              .catch((action) => {});
          } else {
            // 生产日=>非生产日
            if (item.runningFlag === 1) {
              this.setNotWorkDay(item);
            }
            // 非生产日=>生产日
            if (item.runningFlag === 0) {
              this.setWorkDay(item);
            }
            if (!item.id) {
              this.$message.warning('该日期未进行日作业时间配置，您可双击将其设为特定日');
              return;
            }
            // this.dayStatusDialog.isWorkday = item.isWorkday;
            // this.dayStatusDialog.visible = true;
          }
        }, 300); // 在300ms内没有第二次单击则为单击事件
      }
    },
    // 双击
    handleDblClick(item) {
      if (this.timer) {
        // 清除延时器
        clearTimeout(this.timer);
      }
      // 生产日=>特定日
      // 特定日双击编辑
      // 非生产日=>特定日
      this.dblSelectItem(this.dayStatusDialog.dayData);
    },
    setNotWorkDay(item) {
      this.$confirm('是否确认将选中生产日变为非生产日？', '操作', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let params = {
            id: item.id,
            runningFlag: 0
          };
          console.log('params', params);
          calendarSubmitSpecialDay(params)
            .then((res) => {
              this.initTimeDatas(); //  初始化数据
            })
            .catch(() => {});
        })
        .catch((action) => {});
    },
    setWorkDay(item) {
      let params = {};
      params = {
        id: item.id,
        weekday: item.weekday,
        runningFlag: 1,
        workHour: item.workHour,
        jobTimeData: item.jobTimeData,
        sectionId: this.section.data,
        day: item.time
      };
      calendarSubmitSpecialDay(params)
        .then(() => {
          this.initTimeDatas(); //  初始化数据
        })
        .catch(() => {});
    },
    //  将非生产日/生产日 => 特定日
    dblSelectItem(item) {
      this.workTimeConfigTitle = '特定日作业时间设置';
      this.workTimeConfigDialog.time.visible = true;
      this.workTimeAddForm.rowId = item.id;
      this.workTimeAddForm.calendarId = item.calendarId;
      this.workTimeAddForm.calendarDaySchemeId = item.calendarDaySchemeId;
      this.workTimeAddForm.isSpecialDay = item.isSpecialDay;
      this.workTimeAddForm.specialDay = item.time;
      this.workTimeAddForm.runningFlag = item.runningFlag;
      this.workTimeAddForm.details = [
        {
          workHour: item.workHour || 0,
          weekday: item.weekday,
          jobTimeData: [
            {
              jobStartTime: '',
              jobEndTime: ''
            }
          ]
        }
      ];
      let jobTimeData = JSON.parse(item.jobTimeData || '[]');
      if (jobTimeData && jobTimeData.length > 0) {
        this.workTimeAddForm.details[0].jobTimeData = jobTimeData.map((time) => {
          return {
            jobStartTime: time.jobStartTime,
            jobEndTime: time.jobEndTime
          };
        });
      }
    },
    // 过滤日期
    filterTime(arr1, arr2) {
      return arr1.filter((a) => {
        return !arr2.includes(a);
      });
    },
    formatterWeekDay(data) {
      let obj = {
        MONDAY: '周一',
        TUESDAY: '周二',
        WEDNESDAY: '周三',
        THURSDAY: '周四',
        FRIDAY: '周五',
        SATURDAY: '周六',
        SUNDAY: '周日'
      };
      return obj[data];
    },
    // 获取 日作业时间方案
    handleGetCalendarDayTemplateList() {
      const that = this;
      that.workTimeConfigDialog.time.loading = true;
      getCalendarDayTemplateList(that.workTimeConfigDialog.time.page.currentPage, that.workTimeConfigDialog.time.page.pageSize)
        .then((res) => {
          let data = res.data.data;
          data.records.forEach((item) => {
            let details = item.details;
            // item.weekday=item.weekday
            item.weekdayStr = details.map((m) => m.weekday.split(',').map((ss) => this.formatterWeekDay(ss))).join('；');
            item.workHourStr = details.map((m) => m.workHour).join('；');
            item.jobTimeDataStr = details
              .map((m) => {
                let jobTimeData = JSON.parse(m.jobTimeData || '[]');
                return jobTimeData.map((j) => {
                  return j.jobStartTime + '-' + j.jobEndTime;
                });
              })
              .join('；');
          });
          console.log(data.records, 'data.records');
          that.workTimeConfigDialog.time.data = data.records;
          that.workTimeConfigDialog.time.page.total = data.total;
          that.workTimeConfigDialog.time.loading = false;
        })
        .catch((err) => {});
    },
    workTimeConfig() {
      this.workTimeConfigDialog.visible = true;
      this.workTimeConfigDialog.tabsIndex = '1';
      this.workTimeConfigDialog.time.page.currentPage = 1;
      this.workTimeConfigDialog.time.page.pageSize = 20;
      this.handleGetCalendarDayTemplateList();
      this.getAllSectionData();
    },
    // 日作业时间方案 新增
    handleWorkTimeAdd() {
      this.workTimeConfigTitle = '新增';
      this.workTimeConfigDialog.time.visible = true;

      this.$nextTick(() => {
        this.workTimeAddForm.rowId = '';
        this.workTimeAddForm.name = '';
        this.workTimeAddForm.code = '';
        this.workTimeAddForm.details = [
          {
            workHour: '',
            weekday: '',
            jobTimeData: [
              {
                jobStartTime: '',
                jobEndTime: ''
              }
            ]
          }
        ];
        this.$refs['workTimeAddForm'].resetFields();
      });
    },
    // 日作业时间方案 编辑
    handleWorkTimeEdit(row) {
      this.workTimeConfigDialog.time.visible = true;
      this.workTimeConfigTitle = '编辑';
      this.workTimeAddForm.code = row.code;
      this.workTimeAddForm.name = row.name;
      // this.workTimeAddForm.weekday = row.weekday;
      this.workTimeAddForm.rowId = row.id;
      this.workTimeAddForm.details = row.details.map((item) => {
        return {
          ...item,
          jobTimeData: JSON.parse(item.jobTimeData || '[]'),
          weekday: item.weekday.split(',')
        };
      });
    },
    // 日作业时间方案 删除
    workTimeConfigRowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return deleteCalendarDayTemplate(row.id);
        })
        .then(() => {
          this.workTimeConfigDialog.time.page.currentPage = 1;
          this.workTimeConfigDialog.time.page.pageSize = 20;
          this.handleGetCalendarDayTemplateList();
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    // 增加作业时段
    handleAddJobTime(index) {
      this.workTimeAddForm.details[index].jobTimeData.push({
        jobStartTime: '',
        jobEndTime: ''
      });
      this.handleCalculateWorkHour(index);
    },
    // 删除作业时段
    handleDeleteJobTime(index, dIndex) {
      this.workTimeAddForm.details[index].jobTimeData.splice(dIndex, 1);
      this.handleCalculateWorkHour(index);
    },
    checkFromAndToDate(fromDate, toDate) {
      const fromMonth = fromDate.split('-')[1];
      const toMonth = toDate.split('-')[1];
      const fromDay = fromDate.split('-')[2];
      const toDay = toDate.split('-')[2];

      if (fromMonth != '01' || toMonth != '12' || fromDay != '01' || toDay != '31') {
        return false;
      }
      return true;
    },
    // 日历方案 新增
    handleWorkDayAdd(form, done, loading) {
      let isCheck = this.checkFromAndToDate(form.fromDate, form.toDate);
      if (!isCheck) {
        this.$message({
          message: `启用的作业日配置未覆盖1年所有期间，请重新选择`,
          type: 'warning'
        });
        loading();
        return;
      }
      let params = {
        name: form.name,
        code: form.code,
        fromDate: form.fromDate,
        toDate: form.toDate,
        productWorkSectionData: JSON.stringify(form.productWorkSectionData),
        defaultWorkingDay: JSON.stringify(form.defaultWorkingDay)
      };
      console.log(params, 'params');
      initCalendar(params)
        .then(() => {
          done(form);
          this.workTimeConfigDialog.day.page.currentPage = 1;
          this.workTimeConfigDialog.day.page.pageSize = 20;
          this.handleGetCalendarPage();
        })
        .catch((err) => {
          loading();
        });
    },

    // 日历方案 编辑
    handleWorkDayUpdate(form, index, done, loading) {
      let isCheck = this.checkFromAndToDate(form.fromDate, form.toDate);
      if (!isCheck) {
        this.$message({
          message: `启用的作业日配置未覆盖1年所有期间，请重新选择`,
          type: 'warning'
        });
        loading();
        return;
      }
      let params = {
        id: form.id,
        code: form.code,
        name: form.name,
        fromDate: form.fromDate,
        toDate: form.toDate,
        productWorkSectionData: JSON.stringify(form.productWorkSectionData),
        defaultWorkingDay: JSON.stringify(form.defaultWorkingDay)
      };
      console.log(params, 'params');
      initCalendar(params)
        .then(() => {
          done(form);
          this.workTimeConfigDialog.day.page.currentPage = 1;
          this.workTimeConfigDialog.day.page.pageSize = 20;
          this.handleGetCalendarPage();
        })
        .catch(() => {
          loading();
        });
    },
    // 日历方案 删除
    workDayRowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return deleteCalendar(row.id);
        })
        .then(() => {
          this.workTimeConfigDialog.day.page.currentPage = 1;
          this.workTimeConfigDialog.day.page.pageSize = 20;
          this.handleGetCalendarPage();
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },

    isDateIntersection(start1, end1, start2, end2) {
      //1.传进来时间格式：‘08:00’ ‘00:00’ ，这里end1 end2 如果传进来是‘00:00’=‘24:00’
      let startdate1 = start1.split(':')[0][0] === '0' ? Number(start1.split(':')[0][1]) : Number(start1.split(':')[0]);
      let enddate1 = end1.split(':')[0][0] === '0' ? Number(end1.split(':')[0][1]) : Number(end1.split(':')[0]);
      enddate1 = enddate1 == 0 ? 24 : enddate1;
      let startdate2 = start2.split(':')[0][0] === '0' ? Number(start2.split(':')[0][1]) : Number(start2.split(':')[0]);
      let enddate2 = end2.split(':')[0][0] === '0' ? Number(end2.split(':')[0][1]) : Number(end2.split(':')[0]);
      enddate2 = enddate2 == 0 ? 24 : enddate2;
      if (enddate2 <= startdate1 || enddate1 <= startdate2) {
        return false;
      } else {
        return true;
      }
    },
    judge(idx, dateArr) {
      for (let k in dateArr) {
        if (idx !== k) {
          if (dateArr[k].start_time <= dateArr[idx].start_time && dateArr[k].end_time > dateArr[idx].start_time) {
            return false;
          }
          if (dateArr[k].start_time < dateArr[idx].end_time && dateArr[k].end_time >= dateArr[idx].end_time) {
            return false;
          }
        }
      }
      return true;
    },
    verifyTime(dateArr) {
      const that = this;
      let flag = false;
      for (var i = 0; i < dateArr.length; i++) {
        if (flag) return;
        for (var j = 1 + i; j < dateArr.length; j++) {
          if (that.isDateIntersection(dateArr[i][0], dateArr[i][1], dateArr[j][0], dateArr[j][1])) {
            flag = true;
            return;
          }
        }
      }
      return flag;
    },
    // 日作业时间新增/特定日作业时间设置
    workTimeConfigSubmit() {
      this.$refs['workTimeAddForm'].validate((valid) => {
        if (valid) {
          if (this.workTimeAddForm.details.length == 0) {
            this.$message.warning('请设置作业时间');
            return false;
          }
          // if (this.workTimeAddForm.jobTimeData.length == 1 && !this.workTimeAddForm.jobTimeData[0].times[0] && !this.workTimeAddForm.jobTimeData[0].times[1]) {
          //   this.$message.warning('请设置作业时段');
          //   return false;
          // }
          // let { jobTimeData } = this.formatterSubmitParams(this.workTimeAddForm);
          // let verifyJobTime = this.verifyTime(jobTimeData.map((t) => [t.jobStartTime, t.jobEndTime]));
          // if (verifyJobTime !== false) {
          //   this.$message.warning('作业时段有重叠时间，请仔细检查');
          //   return;
          // }

          // let verifyAllTime = this.verifyTime([...jobTimeData.map((t) => [t.jobStartTime, t.jobEndTime]), ...overTimeData.map((t) => [t.overStartTime, t.overEndTime])]);
          // if (verifyAllTime !== false) {
          //   this.$message.warning('加班时段和作业时段有重叠时间，请仔细检查');
          //   return;
          // }
          // let isRepeatJobTime = this.workTimeAddForm.jobTimeData
          //   .map((t) => {
          //     return [t.times[0], t.times[1]];
          //   })
          //   .every((t) => t[0] != t[1]);
          // if (!isRepeatJobTime) {
          //   this.$message.warning('作业时段出现开始和结束时间相同，请仔细检查');
          //   return;
          // }
          if (this.workTimeConfigTitle == '特定日作业时间设置') {
            let params = {};
            console.log(this.workTimeAddForm, 'this.workTimeAddForm');
            params = {
              id: this.workTimeAddForm.rowId,
              day: this.workTimeAddForm.specialDay,
              weekday: this.workTimeAddForm.details[0].weekday,
              runningFlag: 2,
              workHour: this.workTimeAddForm.details[0].workHour,
              jobTimeData: JSON.stringify(this.workTimeAddForm.details[0].jobTimeData),
              sectionId: this.section.data
            };
            console.log(params, 'params');
            calendarSubmitSpecialDay(params)
              .then(() => {
                this.$message.success('设置成功');
                this.workTimeConfigDialog.time.visible = false;
                this.initTimeDatas(); //  初始化数据
              })
              .catch(() => {});
          } else {
            // 检验星期选择是否重复
            let workTimeAddFormDetails = this.workTimeAddForm.details;
            const allWeekdays = workTimeAddFormDetails.reduce((pre, curr) => {
              if (curr.weekday) {
                pre.push(...curr.weekday);
              }
              return pre;
            }, []);
            const uniqueWeekdays = [...new Set(allWeekdays)];
            if (allWeekdays.length !== uniqueWeekdays.length) {
              this.$message.warning('星期选择不能重复,请修改调整');
              return;
            }
            let params = {
              id: this.workTimeAddForm.rowId,
              code: this.workTimeAddForm.code,
              name: this.workTimeAddForm.name,
              details: this.workTimeAddForm.details.map((item) => {
                return {
                  ...item,
                  weekday: item.weekday.join(','),
                  jobTimeData: JSON.stringify(item.jobTimeData)
                };
              })
            };
            console.log(params);
            submitCalendarDayTemplate(params)
              .then(() => {
                this.$message.success(`${this.workTimeConfigTitle}成功`);
                this.workTimeConfigDialog.time.visible = false;
                this.workTimeAddForm.rowId = '';
                this.workTimeAddForm.name = '';
                this.workTimeAddForm.code = '';
                this.workTimeAddForm.details = [
                  {
                    workHour: '',
                    weekday: '',
                    jobTimeData: [
                      {
                        jobStartTime: '',
                        jobEndTime: ''
                      }
                    ]
                  }
                ];
                this.workTimeConfigDialog.time.page.currentPage = 1;
                this.workTimeConfigDialog.time.page.pageSize = 20;
                this.handleGetCalendarDayTemplateList();
              })
              .catch((err) => {});
          }
        } else {
          return false;
        }
      });
    },
    // 计算对应星期的作业工时
    handleCalculateWorkHour(index) {
      let { jobTimeData } = this.formatterSubmitParams(this.workTimeAddForm, index);
      // if (jobTimeData[0] && !jobTimeData[0].jobStartTime && !jobTimeData[0].jobEndTime) {
      //   this.$message.warning('请先选择作业时段的开始时间和结束时间再进行计算工作时长');
      //   return;
      // }
      console.log(jobTimeData, 'jobTimeData');
      let params = {
        jobTimeData: JSON.stringify(jobTimeData)
      };
      calculateWorkHour(params)
        .then((res) => {
          let data = res.data.data;
          this.$set(this.workTimeAddForm.details[index], 'workHour', data);
        })
        .catch(() => {});
    },
    // 获取tab 第二列 作业日分页数据
    handleGetCalendarPage() {
      this.workTimeConfigDialog.day.loading = true;
      getCalendarPage(this.workTimeConfigDialog.day.page.currentPage, this.workTimeConfigDialog.day.page.pageSize)
        .then((res) => {
          let data = res.data.data;
          data.records.forEach((item) => {
            let defaultWorkingDay = JSON.parse(item.defaultWorkingDay || '{}');
            item.defaultFormatterWorkingDay = defaultWorkingDay.schemeName;
          });
          this.workTimeConfigDialog.day.data = data.records;
          this.workTimeConfigDialog.day.page.total = data.total;
          this.workTimeConfigDialog.day.loading = false;
        })
        .catch((err) => {});
    },
    handleTabClick(tab) {
      if (tab.name === '2') {
        this.handleGetWorkDayList();
      } else {
        this.workTimeConfigDialog.time.page.currentPage = 1;
        this.workTimeConfigDialog.time.page.pageSize = 20;
        this.handleGetCalendarDayTemplateList();
      }
    },
    handleGetWorkDayList() {
      this.workTimeConfigDialog.day.page.currentPage = 1;
      this.workTimeConfigDialog.day.page.pageSize = 20;
      this.handleGetCalendarPage();
      getWeekdayKeyValue()
        .then((res) => {
          let data = res.data.data;
          let result = [];
          Object.entries(data).forEach((ele) => {
            result.push({
              label: ele[0],
              value: ele[1][0],
              time: ele[1][1]
              // weekDayKey: ele[1][2]
            });
          });
          this.defaultWorkingDay = result;
          console.log(this.defaultWorkingDay, 'this.defaultWorkingDay');
        })
        .catch((err) => {});
    },
    // 格式化提交参数
    formatterSubmitParams(workTimeAddForm, index) {
      let { jobTimeData } = workTimeAddForm.details[index];
      if (jobTimeData && jobTimeData.length > 0) {
        jobTimeData = jobTimeData
          .map((time) => {
            return {
              jobStartTime: time.jobStartTime,
              jobEndTime: time.jobEndTime
            };
          })
          .filter((time) => time.jobStartTime && time.jobEndTime);
      }
      return {
        jobTimeData
      };
    },
    // 关闭作业时间设置 弹窗
    closeWorkTimeConfigDialog() {
      this.workTimeConfigDialog.visible = false;
      this.initTimeDatas();
      this.getHasSection();
    },
    // 关闭日作业时间方案 新增弹窗
    closeWorkTimeAddFormDialog() {
      console.log(this.workTimeAddForm);
      this.$refs['workTimeAddForm'].resetFields();
      this.workTimeAddForm.name = '';
      this.workTimeAddForm.code = '';
      this.workTimeAddForm.details = [
        {
          workHour: '',
          weekday: '',
          jobTimeData: [
            {
              jobStartTime: '',
              jobEndTime: ''
            }
          ]
        }
      ];

      this.workTimeConfigDialog.time.visible = false;
    },
    // 作业日保存校验
    saveWorkDayConfig() {
      checkCalendar().then((res) => {
        if (res.data.code == 200) {
          let data = res.data.data;
          if (data === 'true') {
            this.closeWorkTimeConfigDialog();
          } else {
            this.$message.error(res.data.data);
          }
        }
      });
    },
    // 日历方案
    beforeWorkDayOpen(done, type) {
      if (type == 'edit') {
        console.log(this.workTimeConfigDialog.day.form);
        let data = this.workTimeConfigDialog.day.form;
        let defaultWorkingDay = JSON.parse(data.defaultWorkingDay || '{}');
        let productWorkSectionData = JSON.parse(data.productWorkSectionData || '[]');
        this.workTimeConfigDialog.day.form.schemeId = defaultWorkingDay.schemeId;
        this.workTimeConfigDialog.day.form.productWorkSectionData = productWorkSectionData;
        this.workTimeConfigDialog.day.form.defaultWorkingDay = defaultWorkingDay;
        this.workTimeConfigDialog.day.form.sectionIds = productWorkSectionData.map((item) => item.sectionId);
      }
      let sectionIdsIndex = this.workTimeConfigDialog.day.option.column.findIndex((item) => item.prop == 'sectionIds');
      let schemeIdIndex = this.workTimeConfigDialog.day.option.column.findIndex((item) => item.prop == 'schemeId');
      this.workTimeConfigDialog.day.option.column[sectionIdsIndex].dicData = this.allSectionData;
      this.workTimeConfigDialog.day.option.column[schemeIdIndex].dicData = this.defaultWorkingDay;
      done();
    },
    nextStep() {
      this.workTimeConfigDialog.tabsIndex = '2';
      this.handleGetWorkDayList();
    },
    handleCloseTimeItem(index) {
      this.workTimeAddForm.details.splice(index, 1);
    },
    handleTimeAddConfig() {
      this.workTimeAddForm.details.push({
        workHour: '',
        weekday: '',
        jobTimeData: [
          {
            jobStartTime: '',
            jobEndTime: ''
          }
        ]
      });
    },
    // 切换作业时间方案
    handleChangeDefaultWorkingDay(value) {
      let find = this.defaultWorkingDay.find((item) => item.value == value);
      this.$set(this.workTimeConfigDialog.day.form, 'defaultWorkingDay', {
        schemeId: find ? find.value : '',
        schemeCode: find ? find.time : '',
        schemeName: find ? find.label : ''
      });
    },
    // 切换使用工段
    handleChangeSectionIds(sectionIds) {
      console.log(sectionIds, 'sectionIds');
      let sectionArr = [];
      sectionIds.map((sectionId) => {
        let find = this.allSectionData.find((item) => item.value == sectionId);
        sectionArr.push({
          sectionId: find ? find.value : '',
          sectionCode: find ? find.code : '',
          sectionName: find ? find.label : ''
        });
      });
      this.$set(this.workTimeConfigDialog.day.form, 'productWorkSectionData', sectionArr);
      console.log(this.workTimeConfigDialog.day.form);
    }
  }
};
</script>

<style lang="scss" scoped>
.calendar-page {
  border: 1px solid #ccc;
  box-sizing: border-box;
  .calendar-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 5px;
    background: #f7f7f7;
    &-title {
      padding-left: 0px;
    }
    .calendar-menu {
      display: flex;
      align-items: center;
      margin: 0px;
      .weekStart {
        font-size: 14px;
        margin-left: 10px;
      }
    }

    &-yaer {
      display: flex;
      align-items: center;
      &-box {
        display: flex;
        align-items: center;
        .color-box {
          width: 45px;
          height: 25px;
          background: #92c0e8;
          border-radius: 50%;
          margin-right: 5px;
          &.default {
            background: #a07d7d24;
          }
          &.today {
            background: #18a058;
          }
          &.special {
            background: #e6a23c;
          }
        }
        .color-label {
          white-space: nowrap;
          margin-right: 10px;
        }
        &-label {
          // width: 50px;
          white-space: nowrap;
          margin-left: 10px;
        }
      }
      .year {
        display: flex;
        align-items: center;
        margin-left: 20px;
        .label {
          font-weight: bold;
        }
      }
    }
  }

  .calendar-content {
    height: 100%;
    background-color: #fff;
    display: grid;
    padding: 5px;
    box-sizing: border-box;
    grid-template-rows: repeat(3, 1fr);
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
    .monthArea {
      .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 5px;
        .time {
          font-weight: bold;
          user-select: none;
        }
      }
      .content {
        position: relative;
        height: calc(100% - 31px);
        margin-left: 30px;
        .content-header {
          height: 30px;
          line-height: 30px;
          display: flex;
          justify-content: space-around;
          .wItem {
            user-select: none;
          }
        }
        .content-wrap {
          font-size: 0;
          .tItem {
            font-size: 14px;
            width: calc(100% / 7 - 6px);
            display: inline-block;
            text-align: center;
            height: 25px;
            line-height: 25px;
            vertical-align: text-top;
            border-radius: 50%;
            margin: 3px;
            box-sizing: border-box;
            user-select: none;
            background: var(--default-bg);
            cursor: pointer;
            &.isActive {
              background: var(--isActive-bg);
              color: #fff;
            }
            &.isSpecialDay {
              background: var(--isSpecialDay-bg);
              color: #fff;
            }
            &.disabled {
              background: #fff;
              color: #000;
              cursor: not-allowed;
            }
            &.today {
              color: #fff;
              background: #18a058;
            }
            &:nth-child(n + 42) {
              display: none;
            }
          }
        }
        .week {
          width: 30px;
          height: calc(100%);
          position: absolute;
          top: 0;
          left: -30px;
          .sitg {
            height: 30px;
            line-height: 30px;
            text-align: center;
            user-select: none;
          }
          .cell {
            height: 25px;
            margin: 3px 6px 6px 6px;
            box-sizing: border-box;
            line-height: 25px;
            text-align: center;
            font-weight: bold;
            user-select: none;
          }
        }
      }
    }
  }
}

::v-deep .workTimeConfigDialog {
  .el-dialog__body {
    padding: 20px;
    .dispatch-title {
      display: flex;
      align-items: center;
      margin: 0 0 10px 0;
      &-dot {
        background-color: rgb(102, 177, 255);
        width: 10px;
        height: 20px;
        margin-right: 8px;
      }
      &-text {
        font-weight: bold;
        font-size: 16px;
      }
    }
    .dispatch-baseInfo {
      .inline {
        display: inline-block;
        width: 40%;
      }
    }
    .timeItemArea {
      max-height: 46vh;
      overflow: scroll;
      .timeItem {
        border: 1px solid #ccc;
        margin-bottom: 5px;
        position: relative;
        .inline {
          display: inline-block;
          width: 50%;
        }
        .closeIcon {
          position: absolute;
          right: 5px;
          top: 5px;
          width: 20px;
          height: 20px;
          z-index: 999;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
        }
        .el-form-item {
          margin-bottom: 20px;
        }
        .addTime,
        .deleteTime {
          margin-left: 10px;
        }
      }
    }

    .timeConfig {
      display: flex;
      margin: 0 auto;
    }
    .specialDayForm {
      .inline {
        display: inline-block;
        width: 50%;
      }
      .workhourArea {
        max-height: 50vh;
        overflow: scroll;
      }
      .addTime,
      .deleteTime {
        margin-left: 10px;
      }
    }
  }
}
::v-deep .dayStatusDialog {
  .el-dialog__body {
    display: none;
  }
}
</style>
